package com.blog.service.impl;

import com.blog.domain.ResponseResult;
import com.blog.domain.entity.LoginUser;
import com.blog.domain.entity.User;
import com.blog.service.LoginService;
import com.blog.utils.JwtUtil;
import com.blog.utils.RedisCache;
import com.blog.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Objects;

@Service
public class LoginServiceImpl implements LoginService {

	@Autowired
	private RedisCache redisCache;

	@Autowired
	private AuthenticationManager authenticationManager;

	@Override
	public ResponseResult login(User user) {
		UsernamePasswordAuthenticationToken authenticationToken = new
				UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());
		Authentication authenticate =
				authenticationManager.authenticate(authenticationToken);
		//判断是否认证通过
		if (Objects.isNull(authenticate)){
			throw new RuntimeException("用户名或者密码错误");
		}
		//通过，获取userid，生成token
		//获取用户
		LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
		String userid = loginUser.getUser().getId().toString();

		String jwt = JwtUtil.createJWT(userid);

		//将用户信息存入redis中
		redisCache.setCacheObject("login"+userid,loginUser);

		HashMap<String,String> map = new HashMap<>();
		map.put("token",jwt);
		return ResponseResult.okResult(map);
	}

	/**退出登录
	 *
	 * @return
	 */
	@Override
	public ResponseResult logout() {

		//获取当前登录的用户id
		Long userId = SecurityUtils.getUserId();
		//删除redis中对应的值
		redisCache.deleteObject("login"+userId);
		return ResponseResult.okResult();
	}
}
